home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / optparse.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  46.1 KB  |  1,414 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """optparse - a powerful, extensible, and easy-to-use option parser.
  5.  
  6. By Greg Ward <gward@python.net>
  7.  
  8. Originally distributed as Optik; see http://optik.sourceforge.net/ .
  9.  
  10. If you have problems with this module, please do not file bugs,
  11. patches, or feature requests with Python; instead, use Optik's
  12. SourceForge project page:
  13.   http://sourceforge.net/projects/optik
  14.  
  15. For support, use the optik-users@lists.sourceforge.net mailing list
  16. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  17. """
  18. __version__ = '1.5a2'
  19. __all__ = [
  20.     'Option',
  21.     'SUPPRESS_HELP',
  22.     'SUPPRESS_USAGE',
  23.     'Values',
  24.     'OptionContainer',
  25.     'OptionGroup',
  26.     'OptionParser',
  27.     'HelpFormatter',
  28.     'IndentedHelpFormatter',
  29.     'TitledHelpFormatter',
  30.     'OptParseError',
  31.     'OptionError',
  32.     'OptionConflictError',
  33.     'OptionValueError',
  34.     'BadOptionError']
  35. __copyright__ = '\nCopyright (c) 2001-2004 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2004 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  36. import sys
  37. import os
  38. import types
  39. import textwrap
  40.  
  41. try:
  42.     from gettext import gettext as _
  43. except ImportError:
  44.     
  45.     _ = lambda arg: arg
  46.  
  47.  
  48. def _repr(self):
  49.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  50.  
  51.  
  52. class OptParseError(Exception):
  53.     
  54.     def __init__(self, msg):
  55.         self.msg = msg
  56.  
  57.     
  58.     def __str__(self):
  59.         return self.msg
  60.  
  61.  
  62.  
  63. class OptionError(OptParseError):
  64.     '''
  65.     Raised if an Option instance is created with invalid or
  66.     inconsistent arguments.
  67.     '''
  68.     
  69.     def __init__(self, msg, option):
  70.         self.msg = msg
  71.         self.option_id = str(option)
  72.  
  73.     
  74.     def __str__(self):
  75.         if self.option_id:
  76.             return 'option %s: %s' % (self.option_id, self.msg)
  77.         else:
  78.             return self.msg
  79.  
  80.  
  81.  
  82. class OptionConflictError(OptionError):
  83.     '''
  84.     Raised if conflicting options are added to an OptionParser.
  85.     '''
  86.     pass
  87.  
  88.  
  89. class OptionValueError(OptParseError):
  90.     '''
  91.     Raised if an invalid option value is encountered on the command
  92.     line.
  93.     '''
  94.     pass
  95.  
  96.  
  97. class BadOptionError(OptParseError):
  98.     '''
  99.     Raised if an invalid or ambiguous option is seen on the command-line.
  100.     '''
  101.     pass
  102.  
  103.  
  104. class HelpFormatter:
  105.     '''
  106.     Abstract base class for formatting option help.  OptionParser
  107.     instances should use one of the HelpFormatter subclasses for
  108.     formatting help; by default IndentedHelpFormatter is used.
  109.  
  110.     Instance attributes:
  111.       parser : OptionParser
  112.         the controlling OptionParser instance
  113.       indent_increment : int
  114.         the number of columns to indent per nesting level
  115.       max_help_position : int
  116.         the maximum starting column for option help text
  117.       help_position : int
  118.         the calculated starting column for option help text;
  119.         initially the same as the maximum
  120.       width : int
  121.         total number of columns for output (pass None to constructor for
  122.         this value to be taken from the $COLUMNS environment variable)
  123.       level : int
  124.         current indentation level
  125.       current_indent : int
  126.         current indentation level (in columns)
  127.       help_width : int
  128.         number of columns available for option help text (calculated)
  129.       default_tag : str
  130.         text to replace with each option\'s default value, "%default"
  131.         by default.  Set to false value to disable default value expansion.
  132.       option_strings : { Option : str }
  133.         maps Option instances to the snippet of help text explaining
  134.         the syntax of that option, e.g. "-h, --help" or
  135.         "-fFILE, --file=FILE"
  136.       _short_opt_fmt : str
  137.         format string controlling how short options with values are
  138.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  139.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  140.         Optik supports.
  141.       _long_opt_fmt : str
  142.         similar but for long options; must be either "%s %s" ("--file FILE")
  143.         or "%s=%s" ("--file=FILE").
  144.     '''
  145.     NO_DEFAULT_VALUE = 'none'
  146.     
  147.     def __init__(self, indent_increment, max_help_position, width, short_first):
  148.         self.parser = None
  149.         self.indent_increment = indent_increment
  150.         self.help_position = self.max_help_position = max_help_position
  151.         if width is None:
  152.             
  153.             try:
  154.                 width = int(os.environ['COLUMNS'])
  155.             except (KeyError, ValueError):
  156.                 width = 80
  157.  
  158.             width -= 2
  159.         
  160.         self.width = width
  161.         self.current_indent = 0
  162.         self.level = 0
  163.         self.help_width = None
  164.         self.short_first = short_first
  165.         self.default_tag = '%default'
  166.         self.option_strings = { }
  167.         self._short_opt_fmt = '%s %s'
  168.         self._long_opt_fmt = '%s=%s'
  169.  
  170.     
  171.     def set_parser(self, parser):
  172.         self.parser = parser
  173.  
  174.     
  175.     def set_short_opt_delimiter(self, delim):
  176.         if delim not in ('', ' '):
  177.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  178.         
  179.         self._short_opt_fmt = '%s' + delim + '%s'
  180.  
  181.     
  182.     def set_long_opt_delimiter(self, delim):
  183.         if delim not in ('=', ' '):
  184.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  185.         
  186.         self._long_opt_fmt = '%s' + delim + '%s'
  187.  
  188.     
  189.     def indent(self):
  190.         self.current_indent += self.indent_increment
  191.         self.level += 1
  192.  
  193.     
  194.     def dedent(self):
  195.         self.current_indent -= self.indent_increment
  196.         if not self.current_indent >= 0:
  197.             raise AssertionError, 'Indent decreased below 0.'
  198.         self
  199.         self.level -= 1
  200.  
  201.     
  202.     def format_usage(self, usage):
  203.         raise NotImplementedError, 'subclasses must implement'
  204.  
  205.     
  206.     def format_heading(self, heading):
  207.         raise NotImplementedError, 'subclasses must implement'
  208.  
  209.     
  210.     def format_description(self, description):
  211.         if not description:
  212.             return ''
  213.         
  214.         desc_width = self.width - self.current_indent
  215.         indent = ' ' * self.current_indent
  216.         return textwrap.fill(description, desc_width, initial_indent = indent, subsequent_indent = indent) + '\n'
  217.  
  218.     
  219.     def expand_default(self, option):
  220.         if self.parser is None or not (self.default_tag):
  221.             return option.help
  222.         
  223.         default_value = self.parser.defaults.get(option.dest)
  224.         if default_value is NO_DEFAULT or default_value is None:
  225.             default_value = self.NO_DEFAULT_VALUE
  226.         
  227.         return option.help.replace(self.default_tag, str(default_value))
  228.  
  229.     
  230.     def format_option(self, option):
  231.         result = []
  232.         opts = self.option_strings[option]
  233.         opt_width = self.help_position - self.current_indent - 2
  234.         if len(opts) > opt_width:
  235.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  236.             indent_first = self.help_position
  237.         else:
  238.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  239.             indent_first = 0
  240.         result.append(opts)
  241.         if option.help:
  242.             help_text = self.expand_default(option)
  243.             help_lines = textwrap.wrap(help_text, self.help_width)
  244.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  245.             []([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  246.         elif opts[-1] != '\n':
  247.             result.append('\n')
  248.         
  249.         return ''.join(result)
  250.  
  251.     
  252.     def store_option_strings(self, parser):
  253.         self.indent()
  254.         max_len = 0
  255.         for opt in parser.option_list:
  256.             strings = self.format_option_strings(opt)
  257.             self.option_strings[opt] = strings
  258.             max_len = max(max_len, len(strings) + self.current_indent)
  259.         
  260.         self.indent()
  261.         for group in parser.option_groups:
  262.             for opt in group.option_list:
  263.                 strings = self.format_option_strings(opt)
  264.                 self.option_strings[opt] = strings
  265.                 max_len = max(max_len, len(strings) + self.current_indent)
  266.             
  267.         
  268.         self.dedent()
  269.         self.dedent()
  270.         self.help_position = min(max_len + 2, self.max_help_position)
  271.         self.help_width = self.width - self.help_position
  272.  
  273.     
  274.     def format_option_strings(self, option):
  275.         '''Return a comma-separated list of option strings & metavariables.'''
  276.         return ', '.join(opts)
  277.  
  278.  
  279.  
  280. class IndentedHelpFormatter(HelpFormatter):
  281.     '''Format help with indented section bodies.
  282.     '''
  283.     
  284.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  285.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  286.  
  287.     
  288.     def format_usage(self, usage):
  289.         return _('usage: %s\n') % usage
  290.  
  291.     
  292.     def format_heading(self, heading):
  293.         return '%*s%s:\n' % (self.current_indent, '', heading)
  294.  
  295.  
  296.  
  297. class TitledHelpFormatter(HelpFormatter):
  298.     '''Format help with underlined section headers.
  299.     '''
  300.     
  301.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  302.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  303.  
  304.     
  305.     def format_usage(self, usage):
  306.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  307.  
  308.     
  309.     def format_heading(self, heading):
  310.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  311.  
  312.  
  313. _builtin_cvt = {
  314.     'int': (int, _('integer')),
  315.     'long': (long, _('long integer')),
  316.     'float': (float, _('floating-point')),
  317.     'complex': (complex, _('complex')) }
  318.  
  319. def check_builtin(option, opt, value):
  320.     (cvt, what) = _builtin_cvt[option.type]
  321.     
  322.     try:
  323.         return cvt(value)
  324.     except ValueError:
  325.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  326.  
  327.  
  328.  
  329. def check_choice(option, opt, value):
  330.     if value in option.choices:
  331.         return value
  332.     else:
  333.         choices = ', '.join(map(repr, option.choices))
  334.         raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  335.  
  336. NO_DEFAULT = ('NO', 'DEFAULT')
  337.  
  338. class Option:
  339.     '''
  340.     Instance attributes:
  341.       _short_opts : [string]
  342.       _long_opts : [string]
  343.  
  344.       action : string
  345.       type : string
  346.       dest : string
  347.       default : any
  348.       nargs : int
  349.       const : any
  350.       choices : [string]
  351.       callback : function
  352.       callback_args : (any*)
  353.       callback_kwargs : { string : any }
  354.       help : string
  355.       metavar : string
  356.     '''
  357.     ATTRS = [
  358.         'action',
  359.         'type',
  360.         'dest',
  361.         'default',
  362.         'nargs',
  363.         'const',
  364.         'choices',
  365.         'callback',
  366.         'callback_args',
  367.         'callback_kwargs',
  368.         'help',
  369.         'metavar']
  370.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'count', 'callback', 'help', 'version')
  371.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'count')
  372.     TYPED_ACTIONS = ('store', 'append', 'callback')
  373.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  374.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  375.     TYPE_CHECKER = {
  376.         'int': check_builtin,
  377.         'long': check_builtin,
  378.         'float': check_builtin,
  379.         'complex': check_builtin,
  380.         'choice': check_choice }
  381.     CHECK_METHODS = None
  382.     
  383.     def __init__(self, *opts, **attrs):
  384.         self._short_opts = []
  385.         self._long_opts = []
  386.         opts = self._check_opt_strings(opts)
  387.         self._set_opt_strings(opts)
  388.         self._set_attrs(attrs)
  389.         for checker in self.CHECK_METHODS:
  390.             checker(self)
  391.         
  392.  
  393.     
  394.     def _check_opt_strings(self, opts):
  395.         opts = filter(None, opts)
  396.         if not opts:
  397.             raise TypeError('at least one option string must be supplied')
  398.         
  399.         return opts
  400.  
  401.     
  402.     def _set_opt_strings(self, opts):
  403.         for opt in opts:
  404.             if len(opt) < 2:
  405.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  406.                 continue
  407.             if len(opt) == 2:
  408.                 if not opt[0] == '-' and opt[1] != '-':
  409.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  410.                 
  411.                 self._short_opts.append(opt)
  412.                 continue
  413.             if not opt[0:2] == '--' and opt[2] != '-':
  414.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  415.             
  416.             self._long_opts.append(opt)
  417.         
  418.  
  419.     
  420.     def _set_attrs(self, attrs):
  421.         for attr in self.ATTRS:
  422.             if attrs.has_key(attr):
  423.                 setattr(self, attr, attrs[attr])
  424.                 del attrs[attr]
  425.                 continue
  426.             if attr == 'default':
  427.                 setattr(self, attr, NO_DEFAULT)
  428.                 continue
  429.             setattr(self, attr, None)
  430.         
  431.         if attrs:
  432.             attrs = attrs.keys()
  433.             attrs.sort()
  434.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  435.         
  436.  
  437.     
  438.     def _check_action(self):
  439.         if self.action is None:
  440.             self.action = 'store'
  441.         elif self.action not in self.ACTIONS:
  442.             raise OptionError('invalid action: %r' % self.action, self)
  443.         
  444.  
  445.     
  446.     def _check_type(self):
  447.         if self.type is None:
  448.             if self.action in self.ALWAYS_TYPED_ACTIONS:
  449.                 if self.choices is not None:
  450.                     self.type = 'choice'
  451.                 else:
  452.                     self.type = 'string'
  453.             
  454.         elif type(self.type) is type:
  455.             self.type = self.type.__name__
  456.         
  457.         if self.type == 'str':
  458.             self.type = 'string'
  459.         
  460.         if self.type not in self.TYPES:
  461.             raise OptionError('invalid option type: %r' % self.type, self)
  462.         
  463.         if self.action not in self.TYPED_ACTIONS:
  464.             raise OptionError('must not supply a type for action %r' % self.action, self)
  465.         
  466.  
  467.     
  468.     def _check_choice(self):
  469.         if self.type == 'choice':
  470.             if self.choices is None:
  471.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  472.             elif type(self.choices) not in (types.TupleType, types.ListType):
  473.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  474.             
  475.         elif self.choices is not None:
  476.             raise OptionError('must not supply choices for type %r' % self.type, self)
  477.         
  478.  
  479.     
  480.     def _check_dest(self):
  481.         if not self.action in self.STORE_ACTIONS:
  482.             pass
  483.         takes_value = self.type is not None
  484.         if self.dest is None and takes_value:
  485.             if self._long_opts:
  486.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  487.             else:
  488.                 self.dest = self._short_opts[0][1]
  489.         
  490.  
  491.     
  492.     def _check_const(self):
  493.         if self.action != 'store_const' and self.const is not None:
  494.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  495.         
  496.  
  497.     
  498.     def _check_nargs(self):
  499.         if self.action in self.TYPED_ACTIONS:
  500.             if self.nargs is None:
  501.                 self.nargs = 1
  502.             
  503.         elif self.nargs is not None:
  504.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  505.         
  506.  
  507.     
  508.     def _check_callback(self):
  509.         if self.action == 'callback':
  510.             if not callable(self.callback):
  511.                 raise OptionError('callback not callable: %r' % self.callback, self)
  512.             
  513.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  514.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  515.             
  516.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  517.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  518.             
  519.         elif self.callback is not None:
  520.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  521.         
  522.         if self.callback_args is not None:
  523.             raise OptionError('callback_args supplied for non-callback option', self)
  524.         
  525.         if self.callback_kwargs is not None:
  526.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  527.         
  528.  
  529.     CHECK_METHODS = [
  530.         _check_action,
  531.         _check_type,
  532.         _check_choice,
  533.         _check_dest,
  534.         _check_const,
  535.         _check_nargs,
  536.         _check_callback]
  537.     
  538.     def __str__(self):
  539.         return '/'.join(self._short_opts + self._long_opts)
  540.  
  541.     __repr__ = _repr
  542.     
  543.     def takes_value(self):
  544.         return self.type is not None
  545.  
  546.     
  547.     def get_opt_string(self):
  548.         if self._long_opts:
  549.             return self._long_opts[0]
  550.         else:
  551.             return self._short_opts[0]
  552.  
  553.     
  554.     def check_value(self, opt, value):
  555.         checker = self.TYPE_CHECKER.get(self.type)
  556.         if checker is None:
  557.             return value
  558.         else:
  559.             return checker(self, opt, value)
  560.  
  561.     
  562.     def convert_value(self, opt, value):
  563.         pass
  564.  
  565.     
  566.     def process(self, opt, value, values, parser):
  567.         value = self.convert_value(opt, value)
  568.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  569.  
  570.     
  571.     def take_action(self, action, dest, opt, value, values, parser):
  572.         if action == 'store':
  573.             setattr(values, dest, value)
  574.         elif action == 'store_const':
  575.             setattr(values, dest, self.const)
  576.         elif action == 'store_true':
  577.             setattr(values, dest, True)
  578.         elif action == 'store_false':
  579.             setattr(values, dest, False)
  580.         elif action == 'append':
  581.             values.ensure_value(dest, []).append(value)
  582.         elif action == 'count':
  583.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  584.         elif action == 'callback':
  585.             if not self.callback_args:
  586.                 pass
  587.             args = ()
  588.             if not self.callback_kwargs:
  589.                 pass
  590.             kwargs = { }
  591.             self.callback(self, opt, value, parser, *args, **kwargs)
  592.         elif action == 'help':
  593.             parser.print_help()
  594.             parser.exit()
  595.         elif action == 'version':
  596.             parser.print_version()
  597.             parser.exit()
  598.         else:
  599.             raise RuntimeError, 'unknown action %r' % self.action
  600.         return 1
  601.  
  602.  
  603. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  604. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  605.  
  606. try:
  607.     (True, False)
  608. except NameError:
  609.     (True, False) = (1, 0)
  610.  
  611.  
  612. try:
  613.     basestring
  614. except NameError:
  615.     basestring = (str, unicode)
  616.  
  617.  
  618. class Values:
  619.     
  620.     def __init__(self, defaults = None):
  621.         if defaults:
  622.             for attr, val in defaults.items():
  623.                 setattr(self, attr, val)
  624.             
  625.         
  626.  
  627.     
  628.     def __str__(self):
  629.         return str(self.__dict__)
  630.  
  631.     __repr__ = _repr
  632.     
  633.     def __eq__(self, other):
  634.         if isinstance(other, Values):
  635.             return self.__dict__ == other.__dict__
  636.         elif isinstance(other, dict):
  637.             return self.__dict__ == other
  638.         else:
  639.             return False
  640.  
  641.     
  642.     def __ne__(self, other):
  643.         return not (self == other)
  644.  
  645.     
  646.     def _update_careful(self, dict):
  647.         '''
  648.         Update the option values from an arbitrary dictionary, but only
  649.         use keys from dict that already have a corresponding attribute
  650.         in self.  Any keys in dict without a corresponding attribute
  651.         are silently ignored.
  652.         '''
  653.         for attr in dir(self):
  654.             if dict.has_key(attr):
  655.                 dval = dict[attr]
  656.                 if dval is not None:
  657.                     setattr(self, attr, dval)
  658.                 
  659.             dval is not None
  660.         
  661.  
  662.     
  663.     def _update_loose(self, dict):
  664.         '''
  665.         Update the option values from an arbitrary dictionary,
  666.         using all keys from the dictionary regardless of whether
  667.         they have a corresponding attribute in self or not.
  668.         '''
  669.         self.__dict__.update(dict)
  670.  
  671.     
  672.     def _update(self, dict, mode):
  673.         if mode == 'careful':
  674.             self._update_careful(dict)
  675.         elif mode == 'loose':
  676.             self._update_loose(dict)
  677.         else:
  678.             raise ValueError, 'invalid update mode: %r' % mode
  679.  
  680.     
  681.     def read_module(self, modname, mode = 'careful'):
  682.         __import__(modname)
  683.         mod = sys.modules[modname]
  684.         self._update(vars(mod), mode)
  685.  
  686.     
  687.     def read_file(self, filename, mode = 'careful'):
  688.         vars = { }
  689.         execfile(filename, vars)
  690.         self._update(vars, mode)
  691.  
  692.     
  693.     def ensure_value(self, attr, value):
  694.         if not hasattr(self, attr) or getattr(self, attr) is None:
  695.             setattr(self, attr, value)
  696.         
  697.         return getattr(self, attr)
  698.  
  699.  
  700.  
  701. class OptionContainer:
  702.     '''
  703.     Abstract base class.
  704.  
  705.     Class attributes:
  706.       standard_option_list : [Option]
  707.         list of standard options that will be accepted by all instances
  708.         of this parser class (intended to be overridden by subclasses).
  709.  
  710.     Instance attributes:
  711.       option_list : [Option]
  712.         the list of Option objects contained by this OptionContainer
  713.       _short_opt : { string : Option }
  714.         dictionary mapping short option strings, eg. "-f" or "-X",
  715.         to the Option instances that implement them.  If an Option
  716.         has multiple short option strings, it will appears in this
  717.         dictionary multiple times. [1]
  718.       _long_opt : { string : Option }
  719.         dictionary mapping long option strings, eg. "--file" or
  720.         "--exclude", to the Option instances that implement them.
  721.         Again, a given Option can occur multiple times in this
  722.         dictionary. [1]
  723.       defaults : { string : any }
  724.         dictionary mapping option destination names to default
  725.         values for each destination [1]
  726.  
  727.     [1] These mappings are common to (shared by) all components of the
  728.         controlling OptionParser, where they are initially created.
  729.  
  730.     '''
  731.     
  732.     def __init__(self, option_class, conflict_handler, description):
  733.         self._create_option_list()
  734.         self.option_class = option_class
  735.         self.set_conflict_handler(conflict_handler)
  736.         self.set_description(description)
  737.  
  738.     
  739.     def _create_option_mappings(self):
  740.         self._short_opt = { }
  741.         self._long_opt = { }
  742.         self.defaults = { }
  743.  
  744.     
  745.     def _share_option_mappings(self, parser):
  746.         self._short_opt = parser._short_opt
  747.         self._long_opt = parser._long_opt
  748.         self.defaults = parser.defaults
  749.  
  750.     
  751.     def set_conflict_handler(self, handler):
  752.         if handler not in ('error', 'resolve'):
  753.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  754.         
  755.         self.conflict_handler = handler
  756.  
  757.     
  758.     def set_description(self, description):
  759.         self.description = description
  760.  
  761.     
  762.     def get_description(self):
  763.         return self.description
  764.  
  765.     
  766.     def _check_conflict(self, option):
  767.         conflict_opts = []
  768.         for opt in option._short_opts:
  769.             if self._short_opt.has_key(opt):
  770.                 conflict_opts.append((opt, self._short_opt[opt]))
  771.                 continue
  772.         
  773.         for opt in option._long_opts:
  774.             if self._long_opt.has_key(opt):
  775.                 conflict_opts.append((opt, self._long_opt[opt]))
  776.                 continue
  777.         
  778.         if conflict_opts:
  779.             handler = self.conflict_handler
  780.             if handler == 'error':
  781.                 raise ', '.join([] % []([ co[0] for co in conflict_opts ]), option)
  782.             elif handler == 'resolve':
  783.                 for opt, c_option in conflict_opts:
  784.                     if opt.startswith('--'):
  785.                         c_option._long_opts.remove(opt)
  786.                         del self._long_opt[opt]
  787.                     else:
  788.                         c_option._short_opts.remove(opt)
  789.                         del self._short_opt[opt]
  790.                     if not c_option._short_opts or c_option._long_opts:
  791.                         c_option.container.option_list.remove(c_option)
  792.                         continue
  793.                 
  794.             
  795.         
  796.  
  797.     
  798.     def add_option(self, *args, **kwargs):
  799.         '''add_option(Option)
  800.            add_option(opt_str, ..., kwarg=val, ...)
  801.         '''
  802.         if type(args[0]) is types.StringType:
  803.             option = self.option_class(*args, **kwargs)
  804.         elif len(args) == 1 and not kwargs:
  805.             option = args[0]
  806.             if not isinstance(option, Option):
  807.                 raise TypeError, 'not an Option instance: %r' % option
  808.             
  809.         else:
  810.             raise TypeError, 'invalid arguments'
  811.         self._check_conflict(option)
  812.         self.option_list.append(option)
  813.         option.container = self
  814.         for opt in option._short_opts:
  815.             self._short_opt[opt] = option
  816.         
  817.         for opt in option._long_opts:
  818.             self._long_opt[opt] = option
  819.         
  820.         if option.dest is not None:
  821.             if option.default is not NO_DEFAULT:
  822.                 self.defaults[option.dest] = option.default
  823.             elif not self.defaults.has_key(option.dest):
  824.                 self.defaults[option.dest] = None
  825.             
  826.         
  827.         return option
  828.  
  829.     
  830.     def add_options(self, option_list):
  831.         for option in option_list:
  832.             self.add_option(option)
  833.         
  834.  
  835.     
  836.     def get_option(self, opt_str):
  837.         if not self._short_opt.get(opt_str):
  838.             pass
  839.         return self._long_opt.get(opt_str)
  840.  
  841.     
  842.     def has_option(self, opt_str):
  843.         if not self._short_opt.has_key(opt_str):
  844.             pass
  845.         return self._long_opt.has_key(opt_str)
  846.  
  847.     
  848.     def remove_option(self, opt_str):
  849.         option = self._short_opt.get(opt_str)
  850.         if option is None:
  851.             option = self._long_opt.get(opt_str)
  852.         
  853.         if option is None:
  854.             raise ValueError('no such option %r' % opt_str)
  855.         
  856.         for opt in option._short_opts:
  857.             del self._short_opt[opt]
  858.         
  859.         for opt in option._long_opts:
  860.             del self._long_opt[opt]
  861.         
  862.         option.container.option_list.remove(option)
  863.  
  864.     
  865.     def format_option_help(self, formatter):
  866.         if not self.option_list:
  867.             return ''
  868.         
  869.         result = []
  870.         for option in self.option_list:
  871.             if option.help is not SUPPRESS_HELP:
  872.                 result.append(formatter.format_option(option))
  873.                 continue
  874.         
  875.         return ''.join(result)
  876.  
  877.     
  878.     def format_description(self, formatter):
  879.         return formatter.format_description(self.get_description())
  880.  
  881.     
  882.     def format_help(self, formatter):
  883.         result = []
  884.         if self.description:
  885.             result.append(self.format_description(formatter))
  886.         
  887.         if self.option_list:
  888.             result.append(self.format_option_help(formatter))
  889.         
  890.         return '\n'.join(result)
  891.  
  892.  
  893.  
  894. class OptionGroup(OptionContainer):
  895.     
  896.     def __init__(self, parser, title, description = None):
  897.         self.parser = parser
  898.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  899.         self.title = title
  900.  
  901.     
  902.     def _create_option_list(self):
  903.         self.option_list = []
  904.         self._share_option_mappings(self.parser)
  905.  
  906.     
  907.     def set_title(self, title):
  908.         self.title = title
  909.  
  910.     
  911.     def format_help(self, formatter):
  912.         result = formatter.format_heading(self.title)
  913.         formatter.indent()
  914.         result += OptionContainer.format_help(self, formatter)
  915.         formatter.dedent()
  916.         return result
  917.  
  918.  
  919.  
  920. class OptionParser(OptionContainer):
  921.     '''
  922.     Class attributes:
  923.       standard_option_list : [Option]
  924.         list of standard options that will be accepted by all instances
  925.         of this parser class (intended to be overridden by subclasses).
  926.  
  927.     Instance attributes:
  928.       usage : string
  929.         a usage string for your program.  Before it is displayed
  930.         to the user, "%prog" will be expanded to the name of
  931.         your program (self.prog or os.path.basename(sys.argv[0])).
  932.       prog : string
  933.         the name of the current program (to override
  934.         os.path.basename(sys.argv[0])).
  935.  
  936.       option_groups : [OptionGroup]
  937.         list of option groups in this parser (option groups are
  938.         irrelevant for parsing the command-line, but very useful
  939.         for generating help)
  940.  
  941.       allow_interspersed_args : bool = true
  942.         if true, positional arguments may be interspersed with options.
  943.         Assuming -a and -b each take a single argument, the command-line
  944.           -ablah foo bar -bboo baz
  945.         will be interpreted the same as
  946.           -ablah -bboo -- foo bar baz
  947.         If this flag were false, that command line would be interpreted as
  948.           -ablah -- foo bar -bboo baz
  949.         -- ie. we stop processing options as soon as we see the first
  950.         non-option argument.  (This is the tradition followed by
  951.         Python\'s getopt module, Perl\'s Getopt::Std, and other argument-
  952.         parsing libraries, but it is generally annoying to users.)
  953.  
  954.       process_default_values : bool = true
  955.         if true, option default values are processed similarly to option
  956.         values from the command line: that is, they are passed to the
  957.         type-checking function for the option\'s type (as long as the
  958.         default value is a string).  (This really only matters if you
  959.         have defined custom types; see SF bug #955889.)  Set it to false
  960.         to restore the behaviour of Optik 1.4.1 and earlier.
  961.  
  962.       rargs : [string]
  963.         the argument list currently being parsed.  Only set when
  964.         parse_args() is active, and continually trimmed down as
  965.         we consume arguments.  Mainly there for the benefit of
  966.         callback options.
  967.       largs : [string]
  968.         the list of leftover arguments that we have skipped while
  969.         parsing options.  If allow_interspersed_args is false, this
  970.         list is always empty.
  971.       values : Values
  972.         the set of option values currently being accumulated.  Only
  973.         set when parse_args() is active.  Also mainly for callbacks.
  974.  
  975.     Because of the \'rargs\', \'largs\', and \'values\' attributes,
  976.     OptionParser is not thread-safe.  If, for some perverse reason, you
  977.     need to parse command-line arguments simultaneously in different
  978.     threads, use different OptionParser instances.
  979.  
  980.     '''
  981.     standard_option_list = []
  982.     
  983.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None):
  984.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  985.         self.set_usage(usage)
  986.         self.prog = prog
  987.         self.version = version
  988.         self.allow_interspersed_args = True
  989.         self.process_default_values = True
  990.         if formatter is None:
  991.             formatter = IndentedHelpFormatter()
  992.         
  993.         self.formatter = formatter
  994.         self.formatter.set_parser(self)
  995.         self._populate_option_list(option_list, add_help = add_help_option)
  996.         self._init_parsing_state()
  997.  
  998.     
  999.     def _create_option_list(self):
  1000.         self.option_list = []
  1001.         self.option_groups = []
  1002.         self._create_option_mappings()
  1003.  
  1004.     
  1005.     def _add_help_option(self):
  1006.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  1007.  
  1008.     
  1009.     def _add_version_option(self):
  1010.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  1011.  
  1012.     
  1013.     def _populate_option_list(self, option_list, add_help = True):
  1014.         if self.standard_option_list:
  1015.             self.add_options(self.standard_option_list)
  1016.         
  1017.         if option_list:
  1018.             self.add_options(option_list)
  1019.         
  1020.         if self.version:
  1021.             self._add_version_option()
  1022.         
  1023.         if add_help:
  1024.             self._add_help_option()
  1025.         
  1026.  
  1027.     
  1028.     def _init_parsing_state(self):
  1029.         self.rargs = None
  1030.         self.largs = None
  1031.         self.values = None
  1032.  
  1033.     
  1034.     def set_usage(self, usage):
  1035.         if usage is None:
  1036.             self.usage = _('%prog [options]')
  1037.         elif usage is SUPPRESS_USAGE:
  1038.             self.usage = None
  1039.         elif usage.startswith('usage:' + ' '):
  1040.             self.usage = usage[7:]
  1041.         else:
  1042.             self.usage = usage
  1043.  
  1044.     
  1045.     def enable_interspersed_args(self):
  1046.         self.allow_interspersed_args = True
  1047.  
  1048.     
  1049.     def disable_interspersed_args(self):
  1050.         self.allow_interspersed_args = False
  1051.  
  1052.     
  1053.     def set_process_default_values(self, process):
  1054.         self.process_default_values = process
  1055.  
  1056.     
  1057.     def set_default(self, dest, value):
  1058.         self.defaults[dest] = value
  1059.  
  1060.     
  1061.     def set_defaults(self, **kwargs):
  1062.         self.defaults.update(kwargs)
  1063.  
  1064.     
  1065.     def _get_all_options(self):
  1066.         options = self.option_list[:]
  1067.         for group in self.option_groups:
  1068.             options.extend(group.option_list)
  1069.         
  1070.         return options
  1071.  
  1072.     
  1073.     def get_default_values(self):
  1074.         if not self.process_default_values:
  1075.             return Values(self.defaults)
  1076.         
  1077.         defaults = self.defaults.copy()
  1078.         for option in self._get_all_options():
  1079.             default = defaults.get(option.dest)
  1080.             if isinstance(default, basestring):
  1081.                 opt_str = option.get_opt_string()
  1082.                 defaults[option.dest] = option.check_value(opt_str, default)
  1083.                 continue
  1084.         
  1085.         return Values(defaults)
  1086.  
  1087.     
  1088.     def add_option_group(self, *args, **kwargs):
  1089.         if type(args[0]) is types.StringType:
  1090.             group = OptionGroup(self, *args, **kwargs)
  1091.         elif len(args) == 1 and not kwargs:
  1092.             group = args[0]
  1093.             if not isinstance(group, OptionGroup):
  1094.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  1095.             
  1096.             if group.parser is not self:
  1097.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  1098.             
  1099.         else:
  1100.             raise TypeError, 'invalid arguments'
  1101.         self.option_groups.append(group)
  1102.         return group
  1103.  
  1104.     
  1105.     def get_option_group(self, opt_str):
  1106.         if not self._short_opt.get(opt_str):
  1107.             pass
  1108.         option = self._long_opt.get(opt_str)
  1109.         if option and option.container is not self:
  1110.             return option.container
  1111.         
  1112.  
  1113.     
  1114.     def _get_args(self, args):
  1115.         if args is None:
  1116.             return sys.argv[1:]
  1117.         else:
  1118.             return args[:]
  1119.  
  1120.     
  1121.     def parse_args(self, args = None, values = None):
  1122.         """
  1123.         parse_args(args : [string] = sys.argv[1:],
  1124.                    values : Values = None)
  1125.         -> (values : Values, args : [string])
  1126.  
  1127.         Parse the command-line options found in 'args' (default:
  1128.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1129.         by default prints the usage message to stderr and calls
  1130.         sys.exit() with an error message.  On success returns a pair
  1131.         (values, args) where 'values' is an Values instance (with all
  1132.         your option values) and 'args' is the list of arguments left
  1133.         over after parsing options.
  1134.         """
  1135.         rargs = self._get_args(args)
  1136.         if values is None:
  1137.             values = self.get_default_values()
  1138.         
  1139.         self.rargs = rargs
  1140.         self.largs = largs = []
  1141.         self.values = values
  1142.         
  1143.         try:
  1144.             stop = self._process_args(largs, rargs, values)
  1145.         except (BadOptionError, OptionValueError):
  1146.             err = None
  1147.             self.error(err.msg)
  1148.  
  1149.         args = largs + rargs
  1150.         return self.check_values(values, args)
  1151.  
  1152.     
  1153.     def check_values(self, values, args):
  1154.         '''
  1155.         check_values(values : Values, args : [string])
  1156.         -> (values : Values, args : [string])
  1157.  
  1158.         Check that the supplied option values and leftover arguments are
  1159.         valid.  Returns the option values and leftover arguments
  1160.         (possibly adjusted, possibly completely new -- whatever you
  1161.         like).  Default implementation just returns the passed-in
  1162.         values; subclasses may override as desired.
  1163.         '''
  1164.         return (values, args)
  1165.  
  1166.     
  1167.     def _process_args(self, largs, rargs, values):
  1168.         """_process_args(largs : [string],
  1169.                          rargs : [string],
  1170.                          values : Values)
  1171.  
  1172.         Process command-line arguments and populate 'values', consuming
  1173.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1174.         false, stop at the first non-option argument.  If true, accumulate any
  1175.         interspersed non-option arguments in 'largs'.
  1176.         """
  1177.         while rargs:
  1178.             arg = rargs[0]
  1179.             if arg == '--':
  1180.                 del rargs[0]
  1181.                 return None
  1182.                 continue
  1183.             if arg[0:2] == '--':
  1184.                 self._process_long_opt(rargs, values)
  1185.                 continue
  1186.             if arg[:1] == '-' and len(arg) > 1:
  1187.                 self._process_short_opts(rargs, values)
  1188.                 continue
  1189.             if self.allow_interspersed_args:
  1190.                 largs.append(arg)
  1191.                 del rargs[0]
  1192.                 continue
  1193.             return None
  1194.  
  1195.     
  1196.     def _match_long_opt(self, opt):
  1197.         """_match_long_opt(opt : string) -> string
  1198.  
  1199.         Determine which long option string 'opt' matches, ie. which one
  1200.         it is an unambiguous abbrevation for.  Raises BadOptionError if
  1201.         'opt' doesn't unambiguously match any long option string.
  1202.         """
  1203.         return _match_abbrev(opt, self._long_opt)
  1204.  
  1205.     
  1206.     def _process_long_opt(self, rargs, values):
  1207.         arg = rargs.pop(0)
  1208.         if '=' in arg:
  1209.             (opt, next_arg) = arg.split('=', 1)
  1210.             rargs.insert(0, next_arg)
  1211.             had_explicit_value = True
  1212.         else:
  1213.             opt = arg
  1214.             had_explicit_value = False
  1215.         opt = self._match_long_opt(opt)
  1216.         option = self._long_opt[opt]
  1217.         if option.takes_value():
  1218.             nargs = option.nargs
  1219.             if len(rargs) < nargs:
  1220.                 if nargs == 1:
  1221.                     self.error(_('%s option requires an argument') % opt)
  1222.                 else:
  1223.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1224.             elif nargs == 1:
  1225.                 value = rargs.pop(0)
  1226.             else:
  1227.                 value = tuple(rargs[0:nargs])
  1228.                 del rargs[0:nargs]
  1229.         elif had_explicit_value:
  1230.             self.error(_('%s option does not take a value') % opt)
  1231.         else:
  1232.             value = None
  1233.         option.process(opt, value, values, self)
  1234.  
  1235.     
  1236.     def _process_short_opts(self, rargs, values):
  1237.         arg = rargs.pop(0)
  1238.         stop = False
  1239.         i = 1
  1240.         for ch in arg[1:]:
  1241.             opt = '-' + ch
  1242.             option = self._short_opt.get(opt)
  1243.             i += 1
  1244.             if not option:
  1245.                 self.error(_('no such option: %s') % opt)
  1246.             
  1247.             if option.takes_value():
  1248.                 if i < len(arg):
  1249.                     rargs.insert(0, arg[i:])
  1250.                     stop = True
  1251.                 
  1252.                 nargs = option.nargs
  1253.                 if len(rargs) < nargs:
  1254.                     if nargs == 1:
  1255.                         self.error(_('%s option requires an argument') % opt)
  1256.                     else:
  1257.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1258.                 elif nargs == 1:
  1259.                     value = rargs.pop(0)
  1260.                 else:
  1261.                     value = tuple(rargs[0:nargs])
  1262.                     del rargs[0:nargs]
  1263.             else:
  1264.                 value = None
  1265.             option.process(opt, value, values, self)
  1266.             if stop:
  1267.                 break
  1268.                 continue
  1269.         
  1270.  
  1271.     
  1272.     def get_prog_name(self):
  1273.         if self.prog is None:
  1274.             return os.path.basename(sys.argv[0])
  1275.         else:
  1276.             return self.prog
  1277.  
  1278.     
  1279.     def expand_prog_name(self, s):
  1280.         return s.replace('%prog', self.get_prog_name())
  1281.  
  1282.     
  1283.     def get_description(self):
  1284.         return self.expand_prog_name(self.description)
  1285.  
  1286.     
  1287.     def exit(self, status = 0, msg = None):
  1288.         if msg:
  1289.             sys.stderr.write(msg)
  1290.         
  1291.         sys.exit(status)
  1292.  
  1293.     
  1294.     def error(self, msg):
  1295.         """error(msg : string)
  1296.  
  1297.         Print a usage message incorporating 'msg' to stderr and exit.
  1298.         If you override this in a subclass, it should not return -- it
  1299.         should either exit or raise an exception.
  1300.         """
  1301.         self.print_usage(sys.stderr)
  1302.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1303.  
  1304.     
  1305.     def get_usage(self):
  1306.         if self.usage:
  1307.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1308.         else:
  1309.             return ''
  1310.  
  1311.     
  1312.     def print_usage(self, file = None):
  1313.         '''print_usage(file : file = stdout)
  1314.  
  1315.         Print the usage message for the current program (self.usage) to
  1316.         \'file\' (default stdout).  Any occurence of the string "%prog" in
  1317.         self.usage is replaced with the name of the current program
  1318.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1319.         or not defined.
  1320.         '''
  1321.         if self.usage:
  1322.             print >>file, self.get_usage()
  1323.         
  1324.  
  1325.     
  1326.     def get_version(self):
  1327.         if self.version:
  1328.             return self.expand_prog_name(self.version)
  1329.         else:
  1330.             return ''
  1331.  
  1332.     
  1333.     def print_version(self, file = None):
  1334.         '''print_version(file : file = stdout)
  1335.  
  1336.         Print the version message for this program (self.version) to
  1337.         \'file\' (default stdout).  As with print_usage(), any occurence
  1338.         of "%prog" in self.version is replaced by the current program\'s
  1339.         name.  Does nothing if self.version is empty or undefined.
  1340.         '''
  1341.         if self.version:
  1342.             print >>file, self.get_version()
  1343.         
  1344.  
  1345.     
  1346.     def format_option_help(self, formatter = None):
  1347.         if formatter is None:
  1348.             formatter = self.formatter
  1349.         
  1350.         formatter.store_option_strings(self)
  1351.         result = []
  1352.         result.append(formatter.format_heading(_('options')))
  1353.         formatter.indent()
  1354.         if self.option_list:
  1355.             result.append(OptionContainer.format_option_help(self, formatter))
  1356.             result.append('\n')
  1357.         
  1358.         for group in self.option_groups:
  1359.             result.append(group.format_help(formatter))
  1360.             result.append('\n')
  1361.         
  1362.         formatter.dedent()
  1363.         return ''.join(result[:-1])
  1364.  
  1365.     
  1366.     def format_help(self, formatter = None):
  1367.         if formatter is None:
  1368.             formatter = self.formatter
  1369.         
  1370.         result = []
  1371.         if self.usage:
  1372.             result.append(self.get_usage() + '\n')
  1373.         
  1374.         if self.description:
  1375.             result.append(self.format_description(formatter) + '\n')
  1376.         
  1377.         result.append(self.format_option_help(formatter))
  1378.         return ''.join(result)
  1379.  
  1380.     
  1381.     def print_help(self, file = None):
  1382.         """print_help(file : file = stdout)
  1383.  
  1384.         Print an extended help message, listing all options and any
  1385.         help text provided with them, to 'file' (default stdout).
  1386.         """
  1387.         if file is None:
  1388.             file = sys.stdout
  1389.         
  1390.         file.write(self.format_help())
  1391.  
  1392.  
  1393.  
  1394. def _match_abbrev(s, wordmap):
  1395.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1396.  
  1397.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1398.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1399.     'words', raise BadOptionError.
  1400.     """
  1401.     if wordmap.has_key(s):
  1402.         return s
  1403.     else:
  1404.         possibilities = _[1]
  1405.         if len(possibilities) == 1:
  1406.             return possibilities[0]
  1407.         elif not possibilities:
  1408.             raise BadOptionError(_('no such option: %s') % s)
  1409.         else:
  1410.             possibilities.sort()
  1411.             raise BadOptionError(_('ambiguous option: %s (%s?)') % (s, ', '.join(possibilities)))
  1412.  
  1413. make_option = Option
  1414.